package com.example.module_motocircle.ui

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.lib_common.Router
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.base.state.Empty
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.IRetryClickListener
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.Success
import com.example.lib_common.base.state.UILoader
import com.example.lib_common.base.state.UIState
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.utils.ToastUtils
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.FragmentMotorCircleBinding
import com.example.module_motocircle.databinding.LayoutCustomTabViewBinding
import com.example.module_motocircle.helper.SeriesPopupMenuRvHelper
import com.example.module_motocircle.model.MotoCircleNavigationItem
import com.example.module_motocircle.ui.information.InformationFragment
import com.example.module_motocircle.ui.post.PostListFragment
import com.example.module_motocircle.ui.search.SearchActivity
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * 1.tab数据
 * 2.全局UI状态组件
 */
@AndroidEntryPoint
@Route(path = Router.Ui.MotorCircleFragment)
class MotorCircleFragment : BaseFragment<MotorCircleViewModel,FragmentMotorCircleBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_motor_circle


    private val mViewModel: MotorCircleViewModel by viewModels()
    private var mPostAdapter: ScreenSlidePagerAdapter? = null
    private var mSelectedPosition: Int = 0

    private lateinit var mUiLoader: UILoader //状态加载

    override fun initView() {
       initUiLoader()
        mBinding.lSearch.setOnClickListener {
            startActivity(Intent(requireActivity(), SearchActivity::class.java))
        }

    }
    fun initUiLoader(){
        mUiLoader = object :UILoader(requireContext()){
            override fun loadSuccessView(container: ViewGroup?): View? {
                return View(requireContext())
            }
        }
        mBinding.lContainer.addView(mUiLoader)
    }

    override fun initData() {
        //请求tab数据
        mViewModel.getFixedNavigationItem()
    }

    override fun initListener() {
        //订阅tab数据
        mViewModel.navigationState.observeWithLifecycle(this){
            when (it) {
                is Success -> {
                    handleNavigationData()
                    mUiLoader.updateState(UIState.SUCCESS)
                }
                is Empty -> {

                    mUiLoader.updateState(UIState.EMPTY)
                }

                is Failed -> {
//                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                   // mUiLoader.updateState(UIState.UN_LOGIN) //测试未登陆
                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                }

                is Loading -> {

                    mUiLoader.updateState(UIState.LOADING)
                }

            }
        }
        //点击重试
        mUiLoader.setOnRetryClickListener(object : IRetryClickListener {
            override fun onRetryClick() {
                //ToastUtils.showLong(requireActivity(),"chongshi")
                initData()
            }
        })
    }

    /**
     * 加载tab数据以及viewpager
     */
    private fun handleNavigationData() {
        initViewPager()
    }
    private var mediator: TabLayoutMediator? = null
    private fun initViewPager() {
        //适配器
        mPostAdapter = ScreenSlidePagerAdapter(mViewModel.mNavigationItem,this)
        mBinding.vp.adapter = mPostAdapter
        //默认选中
        val default = mViewModel.mNavigationItem.find { it.defaultStatus == 1 } //默认选中tab
        mSelectedPosition = if (default == null) 0 else mViewModel.mNavigationItem.indexOf(default)
        mBinding.vp.currentItem = mSelectedPosition
        //预加载机制
        mBinding.vp.offscreenPageLimit = 1
        //viewpager和tablayout联动
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mSelectedPosition = position
                //更新tab选中
            }
        })
        //自定义tab样式
        mediator = TabLayoutMediator(
            mBinding.tabLayout,
            mBinding.vp,
            true,
            true
        ){tab,position ->  //默认样式
            //自定义
            val tabView = DataBindingUtil.inflate<LayoutCustomTabViewBinding>(
                layoutInflater,
                R.layout.layout_custom_tab_view,
                null,
                false
            )
            if (position >= mViewModel.mNavigationItem.size) {
                return@TabLayoutMediator
            }
            val navigation = mViewModel.mNavigationItem[position]
            //判断二级目录，是否选中
            if (navigation.modelList == null || !navigation.modelList.any { it.checked }) {
                tabView.tab.text = navigation.title
            } else {
                tabView.tab.text = navigation.modelList.find { it.checked }?.name
            }
            tabView.ivArrow.visibility = if (navigation.modelList == null) View.GONE else View.VISIBLE
            //点击事件处理
            tabView.lTab.setOnClickListener {
                if (tab.isSelected){//选中，展开二级目录
                    if (navigation.modelList != null) {
                        showPopupList(tabView.lTab, navigation)
                    }
                }else{//未选中--》选中，展开二级目录
                    tab.select()
                    if (navigation.modelList != null) {
                        Handler(Looper.getMainLooper()).postDelayed({
                            showPopupList(
                                tabView.lTab,
                                navigation
                            )
                        }, 400)
                    }
                }
            }
            tab.customView = tabView.root
        }
        mediator?.attach()
    }
    private val popupMenuRvHelper by lazy {
        SeriesPopupMenuRvHelper(layoutInflater) { navigationId, modelItem ->
            //修改数据源
            ToastUtils.showShort(requireActivity(),"点击了${modelItem.name}")
            val clickNavigation = mViewModel.mNavigationItem.find { it.navigationId == navigationId }
            clickNavigation?.modelList!!.forEach {
                it.checked = modelItem.modelId == it.modelId
            }
            mPostAdapter?.notifyDataSetChanged()

        }
    }

    /**
     * 弹出二级目录
     */
    private fun showPopupList(lTab: ConstraintLayout, navigation: MotoCircleNavigationItem) {
        popupMenuRvHelper.bindItems(navigation.navigationId, navigation.modelList!!)
        popupMenuRvHelper.show(lTab)
    }

    override fun onDestroy() {
        super.onDestroy()
        //防止内存泄漏
        mediator?.detach()
        mediator = null


    }

    private inner class ScreenSlidePagerAdapter(private val item: List<MotoCircleNavigationItem>, fa: Fragment) : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int {
            return item.size
        }

        override fun getItemId(position: Int): Long {
            return item[position].navigationId.toLong()//为每个位置(position)的项提供唯一标识符
        }

        override fun createFragment(position: Int): Fragment {
            return when(item[position].type){
                1 ->{
                    val modelItem = item[position].modelList?.find { it.checked }
                    if (modelItem?.modelId == "10001_01"){
                        PostListFragment.newInstance(sortBy = "hot")
                    }else{
                        PostListFragment.newInstance(sortBy = "hot")
                    }
                }
                2 -> PostListFragment.newInstance(sortBy = "new")
                3 -> InformationFragment()
                4 -> PostListFragment.newInstance(ifFocus = 1)
                else -> PostListFragment()
            }
        }

    }

}
